package org.example.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.db.entity.Permission;
import org.example.db.entity.User;
import org.example.db.mapper.UserMapper;
import org.example.security.bo.SecurityUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;

@Service("SecurityUserDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {


    UserMapper userMapper;
    PermissionService permissionService;

    public SecurityUserDetailsService(UserMapper userMapper, PermissionService permissionService) {
        this.userMapper = userMapper;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = this.getUserByUsername(username);
        if(user != null){
            //log.info("用户 {} 生成UserDetails ", username);
            List<Permission> permissionList = permissionService.getPermissionListByUserId(user.getId());
            return new SecurityUserDetails(user, permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    public User getUserByUsername(String username){

        List<User> userList = userMapper.selectList(new QueryWrapper<User>().lambda().eq(User::getUsername, username));

        return userList.get(0);
    }
}
